App.room = App.cable.subscriptions.create "RoomChannel",
  connected: ->
    # Called when the subscription is ready for use on the server

  disconnected: ->
    # Called when the subscription has been terminated by the server

  received: (data) ->
    $('#messages').append data['message']
    if data['current'] != getCookie('user_id')
      alert('你有新消息')
    # alert(getCookie('user_id'))
    # Called when there's incoming data on the websocket for this channel

  speak: (message) ->
    @perform 'speak', message: message, user_id: getCookie('user_id')

  getCookie = (cookieName) ->
    strCookie = document.cookie
    arrCookie = strCookie.split('; ')
    i = 0
    while i < arrCookie.length
      arr = arrCookie[i].split('=')
      if cookieName == arr[0]
        return arr[1]
      i++
    ''

$(document).on 'keypress', '[data-behavior~=room_speaker]', (event) ->
  if event.keyCode is 13 # return = send
    App.room.speak event.target.value
    event.target.value = ""
    event.preventDefault()



